/*
 * mouse.c
 *
 *  Created on: 01/12/09
 *      Author: manu
 */
 
 
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <mouse.h>

typedef struct {
	point_t pos;
	int rightClick;
	int leftClick;
} mouse_t;

static int fd;
static mouse_t mouse;
static unsigned int width, height;

int create_mouse_pointer(unsigned int w, unsigned int h) {
	fd = open("/dev/mouse", O_RDONLY);
	if ( fd == -1 ) {
		printf("ERROR opening mouse device!\n");
		return -1;
	}
	width = w;
	height = h;
	mouse.pos.x = w/2;
	mouse.pos.y = h/2;
	mouse.rightClick = 0;
	mouse.leftClick = 0;  
	return 0;
}

int get_mouse_pos(point_t * p) {
	int nread, x, y, dx, dy;
	mouseevent_t mouse_event;
	
	
	nread = read(fd, &mouse_event, sizeof(mouse_event));
	if ( nread != sizeof(mouse_event) ) {
		p->x = mouse.pos.x;
		p->y = mouse.pos.y;
		return 0;
	}
	
	dx = mouse_event.dx * 10;
	dy = mouse_event.dy * 10;
	
	x = mouse.pos.x + dx;
	y = mouse.pos.y + dy;
	
	if (x < 0) x = 0;
	if (x >= width) x = x % width;
	
	if (y < 0) y = 0;
	if (y >= height) y = y % height; 

	mouse.rightClick = mouse_event.rightClick;
	mouse.leftClick = mouse_event.leftClick;
	
	p->x = mouse.pos.x = x;
	p->y = mouse.pos.y = y;
	return 0;
}

int get_left_pressed(void) {
	return mouse.leftClick;
}
int get_right_pressed(void) {
	return mouse.rightClick;
}